﻿using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Text;
using System.IO.Ports;
using System.Linq;
using System.Management;
using System.Net;

namespace Infrastructure.Device
{
    /// <summary>
    /// 设备信息
    /// </summary>
    public static class MachineInfoUtils
    {
        /// <summary>
        /// 获得硬盘
        /// </summary>
        /// <returns></returns>
        public static string GetHardDiskId()
        {
            try
            {
                ManagementClass mc = new ManagementClass("Win32_PhysicalMedia");

                ManagementObjectCollection moc = mc.GetInstances();
                string strId = null;
                foreach (var mo in moc)
                {
                    strId = mo.Properties["SerialNumber"].Value.ToString().Trim();
                    break;
                }
                return strId;
            }
            catch
            {
                return "unknow";
            }

        }

        /// <summary>
        /// 获取本机的MAC地址
        /// </summary>
        /// <returns></returns>
        public static string GetMacString()
        {
            using (ManagementObjectSearcher s = new ManagementObjectSearcher(
                 @"SELECT * FROM Win32_NetworkAdapter WHERE (MACAddress IS NOT NULL) and PNPDeviceID LIKE 'PCI%'"))
            {
                foreach (var item in s.Get())
                {
                    return item["MacAddress"].ToString();
                }
                s.Dispose();
            }
            return GetHardDiskId();
        }

        /// <summary>
        /// 获取IP地址
        /// </summary>
        /// <returns></returns>
        public static IPAddress[] GetIPs(string hostname = "")
        {
            return Dns.GetHostAddresses(hostname);
        }

        /// <summary>
        /// 获得IPv4地址
        /// </summary>
        /// <param name="hostname"></param>
        /// <returns></returns>
        public static List<IPAddress> GetIPv4S(string hostname = "")
        {
            return GetIPs(hostname).Where(u => u.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).ToList();
        }

        /// <summary>
        /// 获得端口列表
        /// </summary>
        /// <returns></returns>
        public static string[] GetSerialPorts()
        {
            return SerialPort.GetPortNames();
        }

        /// <summary>
        /// 获得本机字体
        /// </summary>
        /// <returns></returns>
        public static List<KeyValuePair<string, string>> GetFonts()
        {
            InstalledFontCollection myFont = new InstalledFontCollection();
            var list = myFont.Families.Where(u => !string.IsNullOrWhiteSpace(u.Name)).Select(u => new KeyValuePair<string, string>(u.Name, u.Name)).ToList();
            return list;
        }
    }
}
